package com.zj.common.util;  
import java.security.Key;
import java.util.Date;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
//前后端分离token验证，跨域外网可访问
public class TokenUtil {
	//自定义验证key
	private final static String API_KEY="zhangjian";
	//过期时间
	private final static long ttlMillis=3600 * 1000;
	
	public static String createJWT(String id, String issuer, String subject) {
		
		//The JWT signature algorithm we will be using to sign the token
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
		 
		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);
		 
		//We will sign our JWT with our ApiKey secret
		byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(API_KEY);
		Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
		 
		  //Let's set the JWT Claims
		JwtBuilder builder = Jwts.builder().setId(id)
		                                .setIssuedAt(now)
		                                .setSubject(subject)
		                                .setIssuer(issuer)
		                                .signWith(signatureAlgorithm, signingKey);
		 
		//if it has been specified, let's add the expiration
		if (ttlMillis >= 0) {
		    long expMillis = nowMillis + ttlMillis;
		    Date exp = new Date(expMillis);
		    builder.setExpiration(exp);
		}
		 
		//Builds the JWT and serializes it to a compact, URL-safe string
		return builder.compact();
		}
	
	
	public static String parseJWT(String jwt) {
		//This line will throw an exception if it is not a signed JWS (as expected)
		try {
			Claims claims = Jwts.parser()        
					   .setSigningKey(DatatypeConverter.parseBase64Binary(API_KEY)).parseClaimsJws(jwt).getBody();
					return claims.getId();
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseUtil.TOKENFALSE_CODE;
		}
		
		}
}  